package com.sgb.kjwl.viewmodel.home;


import android.annotation.SuppressLint;
import android.text.TextUtils;

import androidx.databinding.ObservableField;

import com.google.gson.reflect.TypeToken;
import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.BuildConfig;
import com.sgb.kjwl.api.APIManager;
import com.swgk.core.view.entity.EnterpriseEditEntity;
import com.swgk.core.view.entity.HomeManageMenuEntity;
import com.sgb.kjwl.model.entity.home.MenuManageEntity;
import com.swgk.core.base.api.ICallBack;
import com.sgb.kjwl.model.entity.HomeMenuEntity;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.entity.MenuEntity;
import com.sgb.kjwl.model.entity.home.HomeAdEntity;
import com.sgb.kjwl.model.entity.home.PictureEntity;
import com.sgb.kjwl.model.entity.request.MaterialFilterJson3;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.repository.HomeRepertory;
import com.swgk.core.mmkvutil.CacheMarker;
import com.sgb.kjwl.view.ui.fragment.home.BigHomeFragment3;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.mmkvutil.DatalUtils;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 张家辅
 */
public class BigHomeFragModel3 extends BaseViewModel {
    public ObservableField<MaterialFilterJson3> materialFilterJson = new ObservableField<>(new MaterialFilterJson3());
    private BigHomeFragment3 fragment;
    private HomeRepertory repertory;
    private Map map;

    public BigHomeFragModel3(BigHomeFragment3 fragment, HomeRepertory repertory) {
        this.fragment = fragment;
        this.repertory = repertory;
    }

    @SuppressLint("CheckResult")
    /**
     *获取跳转至商品页面的三级商品分类数据
     */
    public void getCategoryModel() {
        repertory.getCategoryData(repertory.getAreaCode()).subscribe(listBaseEntity -> {
            List<MenuEntity<MenuEntity<MenuEntity>>> baseEntityData = listBaseEntity.getData();
            if (baseEntityData != null && baseEntityData.size() > 0) {
                fragment.showCategoryView(reBuildMenuEntity(baseEntityData));
            }
        }, throwable -> MLog.d(AppConstant.API_LOG, throwable.getMessage()));
    }

    /***
     *修改原数据,每级分类集合数据第一条数据新增“全部”选项
     */
    private List<MenuEntity<MenuEntity<MenuEntity>>> reBuildMenuEntity(List<MenuEntity<MenuEntity<MenuEntity>>> menuEntityList) {

        MenuEntity<MenuEntity<MenuEntity>> children = new MenuEntity<>();
        children.setName("全部");
        children.setId("");
        menuEntityList.add(0, children);

        for (int index0 = 0; index0 < menuEntityList.size(); index0++) {
            List<MenuEntity<MenuEntity>> menuEntityList1 = menuEntityList.get(index0).getDatas();
            if (menuEntityList1 == null) {
                menuEntityList1 = new ArrayList<>();
            }
            MenuEntity<MenuEntity> menuEntity1 = new MenuEntity<>();
            menuEntity1.setName("全部");
            menuEntity1.setId("");
            menuEntityList1.add(0, menuEntity1);
        }

        for (int index0 = 0; index0 < menuEntityList.size(); index0++) {
            List<MenuEntity<MenuEntity>> menuEntityList1 = menuEntityList.get(index0).getDatas();
            if (menuEntityList1 == null) {
                menuEntityList1 = new ArrayList<>();
            }
            for (MenuEntity<MenuEntity> menuEntity : menuEntityList1) {
                List<MenuEntity> menuEntityList2 = menuEntity.getDatas();
                if (menuEntityList2 == null) {
                    menuEntityList2 = new ArrayList<>();
                }
                MenuEntity menuEntity2 = new MenuEntity<>();
                menuEntity2.setName("全部");
                menuEntity2.setId("");
                menuEntityList2.add(0, menuEntity2);
            }
        }
        return menuEntityList;
    }

    public void firstRecommendMenu() {
        APIManager.getInstance().getMaterialAPI().recommendMenuNew().enqueue(new ICallBack<BaseEntity<List<MenuEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<MenuEntity>> data) {
                fragment.setRecommendMenuData(data.getData());
            }
        });
    }

    /**
     * 首页视频滑动接口
     */
    public void videoTypeList(boolean isRefresh) {
        //获取缓存哈希值
        String mHash = DatalUtils.getHashData(MkvUtils.CacheModular, CacheMarker.CacheVideoTapeData);
        Type type = new TypeToken<List<MenuEntity>>() {
        }.getType();
        Object obj = DatalUtils.getInstance().getData(MkvUtils.CacheModular, CacheMarker.CacheVideoTapeData, type);
        if (null != obj && !isRefresh) {
            List<MenuEntity> videoList = (List<MenuEntity>) obj;
            fragment.showVideoType(videoList, "net");
        } else {
            APIManager.getInstance().getBigHomeAPI().videoTypeList().enqueue(new ICallBack<BaseEntity<List<MenuEntity>>>() {
                @Override
                public void onSuccess(BaseEntity<List<MenuEntity>> data) {
                    if (data.getData() == null) {
                        return;
                    }
                    List<MenuEntity> entities = new ArrayList<>();
                    String mHashNet = DatalUtils.getInstance().strToHashKey(data.getData());
                    if (!mHashNet.equals(mHash)) {
                        entities.addAll(data.getData());
                        fragment.showVideoType(data.getData(), "net");
                        DatalUtils.getInstance().putData(MkvUtils.CacheModular, CacheMarker.CacheVideoTapeData, entities);
                    }
                }
            });
        }
    }

    /*
     * 获取大首页广告图数据
     */
    public void getHomeAdData(boolean isRefresh) {
        //获取缓存哈希值
        String mHash = DatalUtils.getHashData(MkvUtils.CacheModular, CacheMarker.CacheAdListData);
        Type type = new TypeToken<HomeAdEntity>() {
        }.getType();
        Object obj = DatalUtils.getInstance().getData(MkvUtils.CacheModular, CacheMarker.CacheAdListData, type);
        if (null != obj && !isRefresh) {
            HomeAdEntity videoList = (HomeAdEntity) obj;
            fragment.showAdType(videoList);
        } else {
            String url = BuildConfig.BASE_URL_BIG_HOME + "v1/app/advertisement/getAppBannerAdv";
            APIManager.getInstance().getBigHomeAPI().getHomeAdData(url).enqueue(new ICallBack<BaseEntity<HomeAdEntity>>() {
                @Override
                public void onSuccess(BaseEntity<HomeAdEntity> data) {
                    if (data.getData() == null) {
                        return;
                    }
                    String mHashNet = DatalUtils.getInstance().strToHashKey(data.getData());
                    if (!mHashNet.equals(mHash)) {
                        fragment.showAdType(data.getData());
                        DatalUtils.getInstance().putData(MkvUtils.CacheModular, CacheMarker.CacheAdListData, data.getData());
                    }
                }


            });

        }
    }

    /**
     * 首页顶部菜单数据
     */
    public void getMenuModel(boolean isrefresh) {
        //获取缓存哈希值
      /*  String mHash = DatalUtils.getHashData(MkvUtils.CacheModular, CacheMarker.CacheMenuModel);
        Type type = new TypeToken<List<List<MenuEntity>>>() {}.getType();
        Object obj = DatalUtils.getInstance().getData(MkvUtils.CacheModular, CacheMarker.CacheMenuModel,type);
        if (null != obj && !isrefresh) {
            List<List<MenuEntity>> videoList = (List<List<MenuEntity>>)obj;
            fragment.showMenuView(videoList);
        }else {
            APIManager.getInstance().getBigHomeAPI().getNewCategory().enqueue(new ICallBack<BaseEntity<List<List<MenuEntity>>>>() {
                @Override
                public void onSuccess(BaseEntity<List<List<MenuEntity>>> response) {
                    if (response.getData() == null) {
                        return;
                    }
                    //获取从网络请求下来的数据的哈希值
                    String mHashNet = DatalUtils.getInstance().strToHashKey(response.getData());
                    //做以对比如果不相等的话直接把新数据替换
                    if (!mHash.equals(mHashNet)) {
                        fragment.showMenuView(response.getData());
                        DatalUtils.getInstance().putData(MkvUtils.CacheModular, CacheMarker.CacheMenuModel, response.getData());
                    } else {
                        fragment.closeRefresh();
                    }
                }
            });
        }*/
    }

    /*
     * 新金刚区列表数据
     *
     * */
    public void getHomeMenuList(boolean isRefresh) {
        //获取缓存哈希值
        String mHash = DatalUtils.getHashData(MkvUtils.CacheModular, CacheMarker.CacheMenuModel);
        Type type = new TypeToken<List<List<HomeManageMenuEntity>>>() {
        }.getType();
        Object obj = DatalUtils.getInstance().getData(MkvUtils.CacheModular, CacheMarker.CacheMenuModel, type);
        if (null != obj && !isRefresh) {
            List<HomeManageMenuEntity> videoList = (List<HomeManageMenuEntity>) obj;
            fragment.showMenuView(videoList);
        } else {
            APIManager.getInstance().getBigHomeAPI().getHomeMenuList("index").enqueue(new ICallBack<BaseEntity<MenuManageEntity<List<HomeManageMenuEntity>>>>() {
                @Override
                public void onSuccess(BaseEntity<MenuManageEntity<List<HomeManageMenuEntity>>> response) {
                    if (response.getData() == null)
                        return;
                    //获取从网络请求下来的数据的哈希值
                    String mHashNet = DatalUtils.getInstance().strToHashKey(response.getData());
                    //做以对比如果不相等的话直接把新数据替换
                    if (!mHash.equals(mHashNet)) {
                        fragment.showMenuView(response.getData().getData());
                        DatalUtils.getInstance().putData(MkvUtils.CacheModular, CacheMarker.CacheMenuModel, response.getData().getData());
                    } else {
                        fragment.closeRefresh();
                    }
                }
            });
        }
    }

    /**
     * 商品分类
     * @param areacode
     */
    public void getMenuModels(String areacode, boolean isrefresh) {
        // DialogHelper.showProgressDialog(fragment.getActivity(), null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        //获取缓存哈希值
        String mHash = DatalUtils.getHashData(MkvUtils.CacheModular, CacheMarker.CacheMenuModelShopTwoType);
        Type type = new TypeToken<List<MenuEntity>>() {
        }.getType();
        Object obj = DatalUtils.getInstance().getData(MkvUtils.CacheModular, CacheMarker.CacheMenuModelShopTwoType, type);
        if (null != obj && !isrefresh) {
            List<MenuEntity> videoList = (List<MenuEntity>) obj;
            fragment.showshopMenuView(videoList);
        } else {
            if (areacode.equals("") || "0".equals(areacode)) {
                areacode = repertory.getAreaCode();
            }
            if (map == null) {
                map = new HashMap();
            }
            map.put("areaCode", areacode);
            APIManager.getInstance().getMaterialAPI().getItemCatList(map).enqueue(new ICallBack<BaseEntity<List<MenuEntity>>>() {
                @Override
                public void onSuccess(BaseEntity<List<MenuEntity>> data) {
                    if (data == null) {
                        return;
                    }
                    if (data.getState().equals(APIManager.RESPONSE_OK)) {
                        List<MenuEntity> entities = new ArrayList<>();
                        String mHashNet = DatalUtils.getInstance().strToHashKey(data.getData());
                        if (!mHashNet.equals(mHash)) {
                            entities.addAll(data.getData());
                            fragment.showshopMenuView(data.getData());
                            DatalUtils.getInstance().putData(MkvUtils.CacheModular, CacheMarker.CacheMenuModelShopTwoType, entities);
                        }
                    } else {
                        MToast.showToast(fragment.getActivity(), data.getMsg());
                    }
                }
            });
        }
    }

    public void recomandCate(boolean isRefresh) {
        Type type = new TypeToken<List<HomeMenuEntity>>() {
        }.getType();
        Object obj = DatalUtils.getInstance().getData(MkvUtils.CacheModular, CacheMarker.HOME_MEAU, type);
        List<HomeMenuEntity> data = new ArrayList<>();
        if (null != obj && isRefresh == false) {
            List<HomeMenuEntity> dataList = (List<HomeMenuEntity>) obj;
            data.addAll(dataList);
            fragment.showRecommendCate(data, isRefresh);
        }
        if (data.size() == 0 || isRefresh){
            getTuijianData(isRefresh);
        }
    }

    /**
     * 获取大首页推荐数据
     * @param isRefresh
     */
    private void getTuijianData(boolean isRefresh) {
        APIManager.getInstance().getBigHomeAPI().getAllRecomandCate().enqueue(new ICallBack<BaseEntity<List<HomeMenuEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<HomeMenuEntity>> data) {
                if (data == null) {
                    return;
                }
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    //获取从网络请求下来的数据的哈希值
                    String mHashNet = DatalUtils.getInstance().strToHashKey(data.getData());
                    if (data.getData() != null && data.getData().size() > 0) {
                        String cacheOperationHash = DatalUtils.getHashData(MkvUtils.CacheModular, CacheMarker.HOME_MEAU);
                        if (!mHashNet.equals(cacheOperationHash)) {
                            fragment.showRecommendCate(data.getData(), false);
                            DatalUtils.getInstance().putData(MkvUtils.CacheModular, CacheMarker.HOME_MEAU, data.getData());
                        } else {
                            fragment.showRecommendCate(data.getData(), isRefresh);
                        }
                    }
                } else {
                    MToast.showToast(fragment.getActivity(), data.getMsg());
                }
            }
        });
    }

    //获取省市区
    public void getAddressModel() {
        Type type = new TypeToken<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>() {
        }.getType();
        Object obj = DatalUtils.getInstance().getData(MkvUtils.CacheModular, CacheMarker.AREA_JSON, type);
        if (obj == null) {
            APIManager.getInstance().getGoodsAPI().getCityList().enqueue(new ICallBack<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>>() {
                @Override
                public void onSuccess(BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>> data) {
                    if (data.getData() == null) return;
                    DatalUtils.getInstance().putData(MkvUtils.CacheModular, CacheMarker.AREA_JSON, data.getData());
                }
            });
        }
    }

    //获取图查信息列表
    public void getPictureList(boolean isRefresh) {
        Type type = new TypeToken<List<PictureEntity>>() {
        }.getType();
        Object obj = DatalUtils.getInstance().getData(MkvUtils.CacheModular, CacheMarker.HOME_MEAU_IMAGE, type);
        List<PictureEntity> data = new ArrayList<>();
        if (null != obj && isRefresh == false) {
            List<PictureEntity> dataList = (List<PictureEntity>) obj;
            data.addAll(dataList);
            fragment.getPictureList(data);
            return;
        }
        APIManager.getInstance().getGoodsAPI().getPictureList().enqueue(new ICallBack<BaseEntity<List<PictureEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<PictureEntity>> data) {
                //获取从网络请求下来的数据的哈希值
                String mHashNet = DatalUtils.getInstance().strToHashKey(data.getData());
                if (data.getData() != null && data.getData().size() > 0) {
                    String cacheOperationHash = DatalUtils.getHashData(MkvUtils.CacheModular, CacheMarker.HOME_MEAU_IMAGE);
                    if (!mHashNet.equals(cacheOperationHash)) {
                        fragment.getPictureList(data.getData());
                        DatalUtils.getInstance().putData(MkvUtils.CacheModular, CacheMarker.HOME_MEAU_IMAGE, data.getData());
                    }else{
                        fragment.getPictureList(data.getData());
                    }
                }
            }
        });
    }

    int i = 0;
    /**
     * 根据用户身份信息获取展示的企业标题
     */
    public void getCompanyTitleList(String areaCode) {
        i ++;
        areaCode = repertory.getAreaCode();
        SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.AREA_CODE, repertory.getAreaCode());
        int code = TextUtils.isEmpty(areaCode)?615000:Integer.valueOf(areaCode);
        APIManager.getInstance().getBigHomeAPI().getEnterpriseRecListNew(code).enqueue(new ICallBack<BaseEntity<List<EnterpriseEditEntity>>>(true, true) {
            @Override
            public void onSuccess(BaseEntity<List<EnterpriseEditEntity>> data) {
                i = 0;
                fragment.initCompanyTitle(data.getData());
            }

            @Override
            public void onFailureWithEntity(BaseEntity entity) {
                super.onFailureSwitchErrCode(entity);
                if (entity != null && i<2){
                    if ("53999".equals(entity.getErrCode())){
                        getCompanyTitleList("");
                    }
                }
            }
        });
    }

    /**
     * 根据企业标题获取类型列表数据
     */
    public void getCompanyList(List<MenuEntity> titleList) {
//        APIManager.getInstance().getBigHomeAPI().getEnterpriseRecList(titleList.get(0).getId()).enqueue(new ICallBack<BaseEntity<List<EnterpriseRecEntity>>>(true, true) {
//            @Override
//            public void onSuccess(BaseEntity<List<EnterpriseRecEntity>> data) {
//                fragment.showMenuList(data.getData());
//            }
//        });
    }

}
